package com.seculab.admin.web;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.seculab.admin.domain.User;
import com.seculab.admin.service.UserService;
import com.seculab.admin.web.validator.UserValidator;

@Controller
@RequestMapping("/company")
@SessionAttributes("user")
public class UserEditController {
	private static final Logger logger = Logger.getLogger(UserEditController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserValidator userValidator;
	
	@RequestMapping("userModifyForm")
	public void userModifyForm(@RequestParam String id, Model model) throws Exception {
		logger.debug("userModifyForm is started");
		model.addAttribute("user", userService.getUser(id));
	}	
	
	@RequestMapping("modifyUser")
	public String modifyUser(@ModelAttribute User user, BindingResult result, SessionStatus sessionStatus) throws Exception {
		logger.debug("modifyUser is started");
		userValidator.validate(user, result);
		
		if(result.hasErrors()) {
			logger.debug("hasErrors is started");
			return "company/userModifyForm";
		}
		
		userService.modifyUser(user);
		sessionStatus.setComplete();
		return "redirect:userList";		
	}
	
}
